using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using WPF_MVVM_Test.MVVM_Model;

namespace WPF_MVVM_Test.Services
{
    /// <summary>
    /// 用户管理API服务类
    /// 负责与后台API进行用户数据的交互
    /// </summary>
    public class UserService
    {
        private readonly HttpClient _httpClient;
        private readonly JsonSerializerOptions _jsonOptions;
        private const string BASE_URL = "http://8.140.51.34:44394/api/app/user";

        /// <summary>
        /// 构造函数
        /// </summary>
        public UserService()
        {
            _httpClient = new HttpClient();
            // 设置默认请求头
            _httpClient.DefaultRequestHeaders.Add("accept", "text/plain");

            // 配置JSON序列化选项
            _jsonOptions = new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true,
                DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
                NumberHandling = JsonNumberHandling.AllowReadingFromString
            };
        }

        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <param name="userName">用户名筛选（可选）</param>
        /// <param name="userEmail">邮箱筛选（可选）</param>
        /// <param name="userPhone">手机号筛选（可选）</param>
        /// <param name="sorting">排序方式，默认为0</param>
        /// <param name="skipCount">跳过数量，默认为0</param>
        /// <param name="maxResultCount">最大返回数量，默认为100</param>
        /// <returns>用户列表</returns>
        public async Task<List<User>> GetUsersAsync(
            string? userName = null,
            string? userEmail = null,
            string? userPhone = null,
            string sorting = "0",
            int skipCount = 0,
            int maxResultCount = 100)
        {
            try
            {
                // 构建查询参数
                var queryParams = new List<string>();

                if (!string.IsNullOrEmpty(userName))
                    queryParams.Add($"UserName={Uri.EscapeDataString(userName)}");

                if (!string.IsNullOrEmpty(userEmail))
                    queryParams.Add($"UserEmail={Uri.EscapeDataString(userEmail)}");

                if (!string.IsNullOrEmpty(userPhone))
                    queryParams.Add($"UserPhone={Uri.EscapeDataString(userPhone)}");

                queryParams.Add($"Sorting={sorting}");
                queryParams.Add($"SkipCount={skipCount}");
                queryParams.Add($"MaxResultCount={maxResultCount}");

                // 构建完整URL
                var queryString = string.Join("&", queryParams);
                var requestUrl = $"{BASE_URL}?{queryString}";

                // 发送GET请求
                var response = await _httpClient.GetAsync(requestUrl);

                if (response.IsSuccessStatusCode)
                {
                    var jsonContent = await response.Content.ReadAsStringAsync();

                    // 解析JSON响应 - 根据实际API返回格式
                    var apiResponse = JsonSerializer.Deserialize<ApiResponseWrapper>(jsonContent, _jsonOptions);

                    return apiResponse?.Data?.Data ?? new List<User>();
                }
                else
                {
                    throw new Exception($"API请求失败: {response.StatusCode} - {response.ReasonPhrase}");
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"获取用户列表失败: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 获取用户列表 - 带超时和静默错误处理
        /// </summary>
        /// <param name="userName">用户名筛选（可选）</param>
        /// <param name="userEmail">邮箱筛选（可选）</param>
        /// <param name="userPhone">手机号筛选（可选）</param>
        /// <param name="sorting">排序方式，默认为0</param>
        /// <param name="skipCount">跳过数量，默认为0</param>
        /// <param name="maxResultCount">最大返回数量，默认为100</param>
        /// <param name="timeoutSeconds">超时时间（秒），默认为3秒</param>
        /// <returns>用户列表，如果请求失败则返回空列表</returns>
        public async Task<List<User>> GetUsersSilentlyAsync(
            string? userName = null,
            string? userEmail = null,
            string? userPhone = null,
            string sorting = "0",
            int skipCount = 0,
            int maxResultCount = 100,
            int timeoutSeconds = 3)
        {
            try
            {
                // 创建取消令牌，设置超时时间
                using var cts = new System.Threading.CancellationTokenSource(TimeSpan.FromSeconds(timeoutSeconds));
                
                // 构建查询参数
                var queryParams = new List<string>();

                if (!string.IsNullOrEmpty(userName))
                    queryParams.Add($"UserName={Uri.EscapeDataString(userName)}");

                if (!string.IsNullOrEmpty(userEmail))
                    queryParams.Add($"UserEmail={Uri.EscapeDataString(userEmail)}");

                if (!string.IsNullOrEmpty(userPhone))
                    queryParams.Add($"UserPhone={Uri.EscapeDataString(userPhone)}");

                queryParams.Add($"Sorting={sorting}");
                queryParams.Add($"SkipCount={skipCount}");
                queryParams.Add($"MaxResultCount={maxResultCount}");

                // 构建完整URL
                var queryString = string.Join("&", queryParams);
                var requestUrl = $"{BASE_URL}?{queryString}";

                // 发送GET请求，带取消令牌
                var response = await _httpClient.GetAsync(requestUrl, cts.Token);

                if (response.IsSuccessStatusCode)
                {
                    var jsonContent = await response.Content.ReadAsStringAsync();

                    // 解析JSON响应
                    var apiResponse = JsonSerializer.Deserialize<ApiResponseWrapper>(jsonContent, _jsonOptions);

                    return apiResponse?.Data?.Data ?? new List<User>();
                }
                
                // 请求失败，返回空列表，不抛出异常
                return new List<User>();
            }
            catch (Exception)
            {
                // 捕获所有异常但不抛出，静默处理
                // 返回空列表
                return new List<User>();
            }
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose()
        {
            _httpClient?.Dispose();
        }
    }

    /// <summary>
    /// API响应包装类 - 根据实际API返回格式
    /// 格式: {"data":{"totleCount":14,"totlePage":2,"data":[...]}}
    /// </summary>
    public class ApiResponseWrapper
    {
        public ApiResponseData? Data { get; set; }
    }

    /// <summary>
    /// API响应数据类
    /// </summary>
    public class ApiResponseData
    {
        public int TotleCount { get; set; }
        public int TotlePage { get; set; }
        public List<User> Data { get; set; } = new List<User>();
    }
}
